import re
import time
import stat
import shutil
import requests
import warnings
from pyquery import PyQuery as pq
import os
import git
import subprocess
import openpyxl
from datetime import datetime
from openpyxl.reader.excel import load_workbook
warnings.filterwarnings('ignore')





def re_info(input_web):
    repository_name,project_name=re.findall("https://gitee.com/(.*?)/(.*?)/",input_web)[0]
    repository='https://gitee.com/'+repository_name+'/'+project_name+'.git'
    # if os.path.exists('./' + repository_name + '/'+project_name+ '/'):
        # os.chmod('./' + repository_name + '/'+project_name+ '/', 0o777)
        # shutil.rmtree('./' + repository_name + '/'+project_name+ '/')
    return repository,repository_name,project_name


def git_back_origin_repository(repo_path):
    try:
        subprocess.run(['git', 'reset', '--hard'], cwd=repo_path)
        print("git reset执行成功")
    except subprocess.CalledProcessError as e:
        print(f"执行错误: {str(e)}")

    try:
        subprocess.run(['git', 'clean', '-dfx'], cwd=repo_path)
        print("git clean执行成功")
    except subprocess.CalledProcessError as e:
        print(f"执行错误 {e.returncode}")

    try:
        subprocess.run(['git', 'pull'], cwd=repo_path)
        print("git pull执行成功")
    except subprocess.CalledProcessError as e:
        print(f"执行错误 {e.returncode}")


def get_respository(repository,repository_name,project_name):
    print('下载项目')
    pattern_path = './' + repository_name + '/' + project_name + '/'
    git.Repo.clone_from(repository,pattern_path)


def get_diff(repository_name,project_name,input_web):
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0'}
    diff_info=requests.get(url=input_web+'.diff',headers=headers,verify=False)
    pattern_path = './' + repository_name + '/' + project_name + '/'
    with open(pattern_path+'{}.diff'.format(project_name),'w',encoding='utf-8') as f:
        f.write(diff_info.text)
    time.sleep(0.2)
    print('执行diff文件')
    put_patch('//home/wenhuanran/tmpte/'+repository_name+'/'+project_name+'/',project_name)
    print('进行编译')
    run_code(repository_name,project_name,input_web)

def put_patch(diff_path,name):
    # 定义要执行的命令
    cd_command = "cd {}".format(diff_path)
    patch_command = 'patch -p1 < {}.diff'.format(name)
    process = subprocess.Popen(['bash', '-c', cd_command + ' && ' + patch_command])
    process.wait()

def run_code(repository_name,project_name,input_web):
    result=subprocess.run(['./run_code.sh',repository_name+'/'+project_name],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
    print(result.stdout)
    result_file='./' + repository_name+'/'+'编译结果'+'/'
    if not os.path.exists(result_file):
        os.makedirs(result_file)
    if '失败' in result.stdout.strip():
        print('失败')
        if os.path.exists(result_file+'{}编译结果.xlsx'.format(get_time()[0])):
            wb=load_workbook(result_file+'{}编译结果.xlsx'.format(get_time()[0]))
            sheet=wb.worksheets[0]
            max_row=sheet.max_row
            sheet.cell(max_row+1,column=1).value=project_name
            sheet.cell(max_row + 1, column=2).value = input_web
            sheet.cell(max_row + 1, column=3).value = get_time()[1]
            wb.save(result_file+'{}编译结果.xlsx'.format(get_time()[0]))
        else:
            wb=openpyxl.Workbook()
            wb.create_sheet('结果',0)
            sheet=wb['结果']
            sheet.append(['名称','网址','时间'])
            sheet.append([project_name, input_web, get_time()[1]])
            wb.save(result_file + '{}编译结果.xlsx'.format(get_time()[0]))
        wb.close()
        with open(result_file + '{}编译失败日志.txt'.format(get_time()[0]), 'a', encoding='utf-8') as f:
            f.write(project_name + '                            ' + input_web + '                            ' + '失败' + '                            ' +get_time()[1])
            f.write('\n')
            f.write(result.stdout)
            f.write('====================================')
            f.write('\n')

    else:
        print('成功')
        with open(result_file + '{}编译结果.txt'.format(get_time()[0]), 'a', encoding='utf-8') as f:
            f.write(project_name + '                  ' + input_web + '                  ' + '成功' + '                   ' +get_time()[1])
            f.write('\n')

def get_time():
    now = datetime.now()
    return str(now.strftime('%Y-%m-%d')),str(now.strftime('%Y-%m-%d_%H:%M'))


def delete_project(repository_name,project_name):
    shutil.rmtree('./' + repository_name + '/' + project_name + '/')




if __name__ == '__main__':
    while True:
        input_web=input('输入地址:')
        repository,repository_name,project_name=re_info(input_web)
        if os.path.exists('./' + repository_name + '/' + project_name + '/'):
            git_back_origin_repository('./' + repository_name + '/' + project_name + '/')
        else:
            get_respository(repository, repository_name, project_name)
        get_diff(repository_name, project_name, input_web)
        # delete_project(repository_name,project_name)

